<?php
// DB Created by Rich L. a member in service in Northern Delaware.  Please feel free to share this code wherever it may be useful to alcholoics.  Should you have questons please contact me at sobernerd@gmail.com
$pageTitle = 'Soberpress - Administration Login';
require_once ('../../config/include_paths.php');
require_once ('config.php');
require_once ('functions.php');
require_once ('dbconnect.php');


if (isset( $_GET['key'])) { // NEW admin user needs to be set up
	$sql= "SELECT randomkey FROM settings";
	$result = mysql_query($sql,$conn);
	while($row = mysql_fetch_array($result))
	  {
	  $dbKey = $row['randomkey'];
	  }
		if ($dbKey ==  $_GET['key']) {
		// looks good now lets create a pw for them
		$password = createRandomPassword();
		$str = DB_NAME.DB_USER.DB_PASS.$password;
		$strHash = hash('md5', $str);
		$sql ="UPDATE settings SET randomkey = '".$strHash."' WHERE id = '1'";
		$result = mysql_query($sql,$conn);
			 ?>
        <body onLoad="document.signin.passwd.focus();">
        <div id="wrapper">
          <div class="padb_cont">
            <?php require_once ('adminHeader.php'); ?>
          </div>
          <div class="clearfloat">&nbsp;</div>
          <h1 class="center">Administrative Logon</h1>
          <form action="newuser.php" method="post" name="new">
            <div>
              <table class="center" border="1" cellspacing="0" cellpadding="3">
              	<tr><td colspan="2"><p>Below is your temporary password.  You may use this or change it on the next page.</p></td></tr>
                <tr>
                  <td>Username:</td>
                  <td><input type="text" name="uname" maxlength="40" value="admin"></td>
                </tr>
                <tr>
                  <td>Password:</td>
                  <td><input type="text" name="passwd" maxlength="50" value="<?php echo $password ?>" readonly></td>
                </tr>
                <tr>
                  <td colspan="2" align="right"><div align="center">
                      <input type="submit" name="submit" value="Submit">
                      <input type="button" value="Cancel" onClick="history.back()">
                    </div></td>
                </tr>
                  </tr>
                
              </table>
              <input type="hidden" name="newUser" value="true">
            </div>
          </form>
        </div>
<?php
	}	
}else{
// note: had to use MULTIPLE HEADERS, VERY IMPORTANT 
// (was the only way to use the php header functiuon to re-direct page after sucessful logon) 

// if form has been submitted and filled in
	$postOK = (  (isset($_POST['submit'])) && (isset($_POST['uname'])) && (isset($_POST['passwd']))  || (isset($_COOKIE['sp_username'])) && (isset($_COOKIE['sp_password']))  );
	if ($postOK) {
		if ((isset($_COOKIE['sp_username'])) && (isset($_COOKIE['sp_password']))) {
			$_POST['uname'] = $_COOKIE['sp_username'];
			$_POST['passwd'] = $_COOKIE['sp_password'];
		}
		// authenticate.
		if (!get_magic_quotes_gpc()) {
		$_POST['uname'] = addslashes($_POST['uname']);
		}
		
		$check = mysql_query("SELECT username, password, admin FROM users WHERE username = '".$_POST['uname']."'");
		
		if (!$check) {
   		 echo 'Could not run query: ' . mysql_error();
    		exit;
		}
			
		if (mysql_num_rows($check) == 0) {
		require_once ('adminhead.php');
	die('That username does not exist in our database. Please <a href="admin.php">try again</a>.');
		}
		
		// return associative array from query
		$info = mysql_fetch_assoc($check);
		// check passwords match
		$_POST['passwd'] = stripslashes($_POST['passwd']);
		$info['password'] = stripslashes($info['password']);
		$postedPW = md5($_POST['passwd']);
		// set variable to use as SESSION admin
		$admin = $info['admin'];
		if ($postedPW  != $info['password']) {
		require_once ('adminhead.php');
	die('Incorrect password, please <a href="admin.php">try again</a>.');
		}

		// if we get here username and password are correct, 
		//register session variables, set cookies and last login time.
		if (isset($_POST['autologin'])) {
            /* Set cookie to last 1 year */
            setcookie('sp_username', $_POST['uname'], time()+60*60*24*365);
            setcookie('sp_password', $_POST['passwd'], time()+60*60*24*365);
        
        } else {
            /* Cookie expires when browser closes */
            setcookie('sp_username', $_POST['uname'], false);
            setcookie('sp_password', $_POST['passwd'], false);
        }
		
		$date = date('Y-m-d H:m:s');

		$update_login = mysql_query("UPDATE users SET last_login = '$date' WHERE username = '".$_POST['uname']."'");

		$_POST['uname'] = stripslashes($_POST['uname']);
		session_start();
		$_SESSION['username'] = $_POST['uname'];
		$_SESSION['password'] = $_POST['passwd'];
		$_SESSION['admin'] = $admin;
		$_SESSION['logged_in'] = 1;
		mysql_close($conn);
		header('Location: settings.php');
		

		 
} else {	
require_once ('adminhead.php');
?>
<body onload="document.signin.uname.focus();">
<div id="wrapper">
  <div class="padb_cont">
    <?php require_once ('adminHeader.php'); ?>
  </div>
  <div class="clearfloat">&nbsp;</div>
  <h1 class="center">Administrative Logon</h1>
  <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" name="signin">
    <div>
      <table class="center" border="1" cellspacing="0" cellpadding="3">
        <tr>
          <td>Username:</td>
          <td><input type="text" name="uname" maxlength="40"></td>
        </tr>
        <tr>
          <td>Password:</td>
          <td><input type="password" name="passwd" maxlength="50"></td>
        </tr>
        <tr>
          <td colspan="2"><input type="checkbox" name="autologin" value="1">
            Remember Me</td>
        </tr>
        <tr>
          <td colspan="2" align="right"><div align="center">
              <input type="submit" name="submit" value="Login">
              <input type="button" value="Cancel" onClick="history.back()">
            </div></td>
        </tr>
          </tr>
        
      </table>
    </div>
  </form>
</div>
<?php
}
}?>
</body>
</html>